package com.iflytek.elpmobile.utils.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.os.AsyncTask;

import com.iflytek.elpmobile.utils.Logging;
import com.iflytek.elpmobile.utils.ReadFileUtils;
import com.simple.elpmobile.utils.network.model.NetworkStatus;
import com.simple.elpmobile.utils.network.model.NetworkStatusListener;
import com.simple.elpmobile.utils.network.model.NetworkStatusReason;

public class HttpGetTask extends AbstractTask
{
	private static final String TAG = "HttpGetTask";
	
	
	public static final int TIME_OUT = 10 * 1000;
	
	private AsyncHttpGetTask mAsyncTask;
	
	public HttpGetTask(String url, NetworkStatusListener statusListener) 
	{
		super(url, statusListener);
	}

	@Override
	public boolean init() 
	{
		if (NetworkStatus.Create != mNetworkInfo.getStatus()) return false;
		
		mAsyncTask = new AsyncHttpGetTask();
		this.onProcess(0, NetworkStatus.Init, NetworkStatusReason.OK);
		return true;
	}

	@Override
	public void start() 
	{
		if (NetworkStatus.Init != mNetworkInfo.getStatus()) 
		{
			if (!init()) return;
		}
		
		mAsyncTask.execute(mURL);
	}

	@Override
	public void finish(NetworkStatus status, NetworkStatusReason reason) 
	{
		this.onProcess(100, status, reason);
	}

	private class AsyncHttpGetTask extends AsyncTask<URL, Integer, TaskInfo>
	{
		
		@Override
		protected TaskInfo doInBackground(URL... params) 
		{
			TaskInfo taskInfo = HttpGetTask.this.mNetworkInfo;
			StringBuilder builder = new StringBuilder();
			
			BufferedReader bufferedReader = null;
			InputStreamReader inputStreamReader = null;
			HttpResponse getHttpResponse = null;
			HttpGet httpGet = null;
			HttpClient httpClient = new DefaultHttpClient();
			
			// 请求超时
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);

			do
			{
				try 
				{
					httpGet = new HttpGet(params[0].toString());
				} 
				catch (IllegalArgumentException e) 
				{
					Logging.e(TAG, String.format("new HttpGet Error!e.getMessage:%s", e.getMessage()));
					
					taskInfo.setStatus(NetworkStatus.Fail);
					taskInfo.setReason(NetworkStatusReason.ConnectionError);
					break;
				}
				
				try 
				{
					getHttpResponse = httpClient.execute(httpGet);
					if (getHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
					{
						inputStreamReader = new InputStreamReader(getHttpResponse
								.getEntity().getContent());
						bufferedReader = new BufferedReader(inputStreamReader);
						
						String line = null;
						while(!mNeedCancel && null != (line = bufferedReader.readLine()))
						{
							builder.append(line);
						}
						
						if (mNeedCancel)
						{
							taskInfo.setStatus(NetworkStatus.Cancel);
							taskInfo.setReason(NetworkStatusReason.OK);
							break;
						}
					}
					else
					{
						throw new ClientProtocolException("getHttpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK");
					}
					
					taskInfo.setStatus(NetworkStatus.Success);
					taskInfo.setReason(NetworkStatusReason.OK);					
					HttpGetTask.this.mNetworkInfo.setResult(builder.toString());
				} 
				catch (Exception e) 
				{
					Logging.e(TAG, String.format("doInBackground Error!e.getMessage:%s", e.getMessage()));
					
					taskInfo.setStatus(NetworkStatus.Fail);
					taskInfo.setReason(NetworkStatusReason.NetError);
					break;
				} 
				finally 
				{
					ReadFileUtils.closeCloseable(bufferedReader);
					ReadFileUtils.closeCloseable(inputStreamReader);
					httpClient.getConnectionManager().shutdown();
				}
			}
			while(false);
			
			
			return taskInfo;
		}
		
		@Override
	    protected void onPostExecute(TaskInfo taskInfo) 
		{
			HttpGetTask.this.finish(taskInfo.getStatus(), taskInfo.getReason());
		}
	}
}
